package com.zymail.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zymail.bean.ZyCollect;
import com.zymail.service.ZyCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/collect")
public class CollectController extends BaseController {

    @Autowired
    ZyCollectService collectService;

    /**
     * 得到一个人所有的收藏
     * @param session_key   session_key
     * @return  List<ZyCollect>
     */
    @RequestMapping("/getcollect/{session_key}")
    public List<ZyCollect> getmycollect(@PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        return collectService.getcollect(userId);
    }

    /**
     * 保存
     * @param session_key session_key
     * @param good_id   需要收藏的商品id
     * @return  boolean
     */
    @PostMapping("/savecollect/{session_key}/{good_id}")
    public boolean savecollect(@PathVariable("session_key") String session_key, @PathVariable("good_id") Integer good_id){
        Integer userId = get_userId(session_key);
        if(userId == 0) return false;

        QueryWrapper<ZyCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("good_id", good_id);
        if(collectService.getOne(wrapper) == null){
            return collectService.save(new ZyCollect(null, userId, good_id, null));
        }
        return false;
    }

    /**
     * 删除
     * @param session_key session_key
     * @param good_id   需要删除的goodid
     * @return  boolean
     */
    @DeleteMapping("/delcollect/{session_key}/{good_id}")
    public boolean delcollect(@PathVariable("session_key") String session_key, @PathVariable("good_id") Integer good_id){
        Integer userId = get_userId(session_key);
        if(userId == 0) return false;

        QueryWrapper<ZyCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("good_id", good_id);
        ZyCollect collect = collectService.getOne(wrapper);
        if(collect != null){
            return collectService.removeById(collect);
        }
        return false;
    }
}
